package com.xoomworks.rsfr.core.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.xoomworks.rsfr.core.service.AuthenticationService;
import com.xoomworks.rsfr.model.User;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    @Autowired
    private RestTemplate restTemplate;

    public static User authenticatedUser;



    @Override
    public User login(final String email, final String password) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("email", email);
        headers.set("password", password);
        headers.set("appKey", "chrome");

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);

        HttpEntity<User> requestEntity = new HttpEntity<User>(null, headers);

        ResponseEntity<User> returnedUser = restTemplate.exchange(
                "http://localhost:8080/RS/LogOn", HttpMethod.GET, requestEntity,
                User.class);

        AuthenticationServiceImpl.authenticatedUser = returnedUser.getBody();
        AuthenticationServiceImpl.authenticatedUser.setPassword(password);

        return AuthenticationServiceImpl.authenticatedUser;
    }

    public static void setAuthenticationHeader (final HttpHeaders headers){
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("email", authenticatedUser.getEmail());
        headers.set("password",authenticatedUser.getPassword());
        headers.set("appKey", "chrome");
    }

}
